import 'package:chewie_audio/chewie_audio.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
import 'package:flutter/foundation.dart';

class VideoProgressBar extends StatefulWidget {
  VideoProgressBar(
    this.controller, {
    ChewieProgressColors? colors,
    this.onDragEnd,
    this.onDragStart,
    this.onDragUpdate,
    Key? key,
    required this.barHeight,
    required this.handleHeight,
    required this.drawShadow,
  })  : colors = colors ?? ChewieProgressColors(),
        super(key: key);

  final VideoPlayerController controller;
  final ChewieProgressColors colors;
  final Function()? onDragStart;
  final Function()? onDragEnd;
  final Function()? onDragUpdate;

  final double barHeight;
  final double handleHeight;
  final bool drawShadow;

  @override
  // ignore: library_private_types_in_public_api
  _VideoProgressBarState createState() {
    return _VideoProgressBarState();
  }
}

class _VideoProgressBarState extends State<VideoProgressBar> {
  void listener() {
    if (!mounted) return;
    // 打印VideoPlayerValue的获取状态
    debugPrint('VideoPlayerValue listener触发:');
    debugPrint('  - isInitialized: ${controller.value.isInitialized}');
    debugPrint('  - 总时间duration: ${controller.value.duration}');
    debugPrint('  - 当前播放时间position: ${controller.value.position}');
    debugPrint('  - isPlaying: ${controller.value.isPlaying}');
    debugPrint('  - buffered: ${controller.value.buffered.length}个缓冲区间');
    setState(() {});
  }

  bool _controllerWasPlaying = false;

  Offset? _latestDraggableOffset;

  VideoPlayerController get controller => widget.controller;

  @override
  void initState() {
    super.initState();
    // 打印初始状态
    debugPrint('VideoProgressBar初始化:');
    debugPrint('  - controller是否为空: ${controller != null}');
    debugPrint('  - 初始isInitialized: ${controller.value.isInitialized}');
    debugPrint('  - 初始duration: ${controller.value.duration}');
    controller.addListener(listener);
  }

  @override
  void deactivate() {
    debugPrint('VideoProgressBar deactivate - 移除监听器');
    controller.removeListener(listener);
    super.deactivate();
  }

  void _seekToRelativePosition(Offset globalPosition) {
    debugPrint('开始跳转定位:');
    debugPrint('  - 当前duration: ${controller.value.duration}');
    debugPrint('  - 当前position: ${controller.value.position}');
    debugPrint('  - 目标globalPosition: $globalPosition');
    final newPosition = context.calcRelativePosition(
      controller.value.duration,
      globalPosition,
    );
    debugPrint('  - 计算后的newPosition: $newPosition');

    controller.seekTo(newPosition);
    // controller.seekTo(context.calcRelativePosition(
    //   controller.value.duration,
    //   globalPosition,
    // ));

  }

  @override
  Widget build(BuildContext context) {
    final ChewieAudioController chewieController =
        ChewieAudioController.of(context);

    // 打印build时的状态
    debugPrint('VideoProgressBar build调用:');
    debugPrint('  - controller.value: ${controller.value}');
    debugPrint('  - isInitialized: ${controller.value.isInitialized}');
    debugPrint('  - draggableProgressBar: ${chewieController.draggableProgressBar}');
    debugPrint('  - _latestDraggableOffset: $_latestDraggableOffset');
    final child = Center(
      child: StaticProgressBar(
        value: controller.value,
        colors: widget.colors,
        barHeight: widget.barHeight,
        handleHeight: widget.handleHeight,
        drawShadow: widget.drawShadow,
        latestDraggableOffset: _latestDraggableOffset,
      ),
    );
    // final child = Center(
    //   child: StaticProgressBar(
    //     value: controller.value,
    //     colors: widget.colors,
    //     barHeight: widget.barHeight,
    //     handleHeight: widget.handleHeight,
    //     drawShadow: widget.drawShadow,
    //   ),
    // );

    return chewieController.draggableProgressBar
        ? GestureDetector(
      onHorizontalDragStart: (DragStartDetails details) {
        debugPrint('拖动开始:');
        debugPrint('  - isInitialized: ${controller.value.isInitialized}');
        debugPrint('  - 是否在播放: ${controller.value.isPlaying}');

        if (!controller.value.isInitialized) {
          debugPrint('  错误: controller未初始化!');
          return;
        }

        _controllerWasPlaying = controller.value.isPlaying;
        if (_controllerWasPlaying) {
          debugPrint('  暂停播放');
          controller.pause();
        }

        widget.onDragStart?.call();
      },
      onHorizontalDragUpdate: (DragUpdateDetails details) {
        if (!controller.value.isInitialized) {
          return;
        }

        _latestDraggableOffset = details.globalPosition;
        debugPrint('拖动更新: $_latestDraggableOffset');

        if (mounted) {
          setState(() {});
        }

        widget.onDragUpdate?.call();
      },
      onHorizontalDragEnd: (DragEndDetails details) {
        debugPrint('拖动结束:');
        debugPrint('  - _controllerWasPlaying: $_controllerWasPlaying');

        if (_controllerWasPlaying) {
          debugPrint('  恢复播放');
          controller.play();
        }

        if (_latestDraggableOffset != null) {
          debugPrint('  执行跳转定位');
          _seekToRelativePosition(_latestDraggableOffset!);
          _latestDraggableOffset = null;
        }

        widget.onDragEnd?.call();
      },
      onTapDown: (TapDownDetails details) {
        debugPrint('点击进度条:');
        debugPrint('  - isInitialized: ${controller.value.isInitialized}');

        if (!controller.value.isInitialized) {
          return;
        }

        _seekToRelativePosition(details.globalPosition);
      },
      child: child,
    )
        : child;

    // return chewieController.draggableProgressBar
    //     ? GestureDetector(
    //         onHorizontalDragStart: (DragStartDetails details) {
    //           if (!controller.value.isInitialized) {
    //             return;
    //           }
    //           _controllerWasPlaying = controller.value.isPlaying;
    //           if (_controllerWasPlaying) {
    //             controller.pause();
    //           }
    //
    //           widget.onDragStart?.call();
    //         },
    //         onHorizontalDragUpdate: (DragUpdateDetails details) {
    //           if (!controller.value.isInitialized) {
    //             return;
    //           }
    //           _latestDraggableOffset = details.globalPosition;
    //           // listener();
    //           // 强制触发UI更新，不依赖于controller的状态变化
    //           if (mounted) {
    //             setState(() {});
    //           }
    //
    //           widget.onDragUpdate?.call();
    //         },
    //         onHorizontalDragEnd: (DragEndDetails details) {
    //           if (_controllerWasPlaying) {
    //             controller.play();
    //           }
    //
    //           if (_latestDraggableOffset != null) {
    //             _seekToRelativePosition(_latestDraggableOffset!);
    //             _latestDraggableOffset = null;
    //           }
    //
    //           widget.onDragEnd?.call();
    //         },
    //         onTapDown: (TapDownDetails details) {
    //           if (!controller.value.isInitialized) {
    //             return;
    //           }
    //           _seekToRelativePosition(details.globalPosition);
    //         },
    //         child: child,
    //       )
    //     : child;
  }
}

class StaticProgressBar extends StatelessWidget {
  const StaticProgressBar({
    Key? key,
    required this.value,
    required this.colors,
    required this.barHeight,
    required this.handleHeight,
    required this.drawShadow,
    this.latestDraggableOffset,
  }) : super(key: key);

  final Offset? latestDraggableOffset;
  final VideoPlayerValue value;
  final ChewieProgressColors colors;

  final double barHeight;
  final double handleHeight;
  final bool drawShadow;

  @override
  Widget build(BuildContext context) {
    // 打印传入的VideoPlayerValue
    debugPrint('StaticProgressBar build:');
    debugPrint('  - value.isInitialized: ${value.isInitialized}');
    debugPrint('  - value.duration: ${value.duration}');
    debugPrint('  - value.position: ${value.position}');
    debugPrint('  - buffered数量: ${value.buffered.length}');
    debugPrint('  - latestDraggableOffset: $latestDraggableOffset');

    // 计算拖动位置
    final draggableValue = latestDraggableOffset != null && value.isInitialized
        ? context.calcRelativePosition(
      value.duration,
      latestDraggableOffset,
    )
        : Duration.zero;

    debugPrint('  - 计算后的draggableValue: $draggableValue');
    // 创建一个新的VideoPlayerValue副本，确保UI能正确显示拖动位置
    // 即使在缓冲状态下
    final displayValue = latestDraggableOffset != null && value.isInitialized
        ? value.copyWith(
            position: context.calcRelativePosition(
              value.duration,
              latestDraggableOffset,
            ),
          )
        : value;

    return Container(
      height: MediaQuery.of(context).size.height,
      width: MediaQuery.of(context).size.width,
      color: Colors.transparent,
      child:
      // CustomPaint(
      //   painter: _ProgressBarPainter(
      //     value: value,
      //     draggableValue: draggableValue,
      //     colors: colors,
      //     barHeight: barHeight,
      //     handleHeight: handleHeight,
      //     drawShadow: drawShadow,
      //   ),
      // ),
      CustomPaint(
        painter: _ProgressBarPainter(
          value: value,
          draggableValue: context.calcRelativePosition(
            value.duration,
            latestDraggableOffset,
          ),
          colors: colors,
          barHeight: barHeight,
          handleHeight: handleHeight,
          drawShadow: drawShadow,
        ),
      ),
    );
  }
}

class _ProgressBarPainter extends CustomPainter {
  _ProgressBarPainter({
    required this.value,
    required this.colors,
    required this.barHeight,
    required this.handleHeight,
    required this.drawShadow,
    required this.draggableValue,
  }) {
    // 打印Painter构造时的值
    debugPrint('_ProgressBarPainter构造:');
    debugPrint('  - value.isInitialized: ${value.isInitialized}');
    debugPrint('  - value.duration: ${value.duration}');
    debugPrint('  - draggableValue: $draggableValue');
  }

  VideoPlayerValue value;
  ChewieProgressColors colors;

  final double barHeight;
  final double handleHeight;
  final bool drawShadow;
  final Duration draggableValue;

  @override
  bool shouldRepaint(CustomPainter painter) {
    final shouldRepaint = true; // 添加逻辑判断是否需要重绘
    debugPrint('添加逻辑判断是否需要重绘shouldRepaint: $shouldRepaint');
    return true;
  }

  @override
  void paint(Canvas canvas, Size size) {
    debugPrint('开始绘制进度条:');
    debugPrint('  - size: $size');
    debugPrint('  - isInitialized: ${value.isInitialized}');

    if (!value.isInitialized) {
      debugPrint('  警告: value未初始化，跳过绘制');
      return;
    }
    final baseOffset = size.height / 2 - barHeight / 2;

    canvas.drawRRect(
      RRect.fromRectAndRadius(
        Rect.fromPoints(
          Offset(0.0, baseOffset),
          Offset(size.width, baseOffset + barHeight),
        ),
        const Radius.circular(4.0),
      ),
      colors.backgroundPaint,
    );
    if (!value.isInitialized) {
      return;
    }
    final double playedPartPercent = (draggableValue != Duration.zero
            ? draggableValue.inMilliseconds
            : value.position.inMilliseconds) /
        value.duration.inMilliseconds;
    final double playedPart =
        playedPartPercent > 1 ? size.width : playedPartPercent * size.width;
    for (final DurationRange range in value.buffered) {
      final double start = range.startFraction(value.duration) * size.width;
      final double end = range.endFraction(value.duration) * size.width;
      canvas.drawRRect(
        RRect.fromRectAndRadius(
          Rect.fromPoints(
            Offset(start, baseOffset),
            Offset(end, baseOffset + barHeight),
          ),
          const Radius.circular(4.0),
        ),
        colors.bufferedPaint,
      );
    }
    canvas.drawRRect(
      RRect.fromRectAndRadius(
        Rect.fromPoints(
          Offset(0.0, baseOffset),
          Offset(playedPart, baseOffset + barHeight),
        ),
        const Radius.circular(4.0),
      ),
      colors.playedPaint,
    );

    if (drawShadow) {
      final Path shadowPath = Path()
        ..addOval(
          Rect.fromCircle(
            center: Offset(playedPart, baseOffset + barHeight / 2),
            radius: handleHeight,
          ),
        );

      canvas.drawShadow(shadowPath, Colors.black, 0.2, false);
    }

    canvas.drawCircle(
      Offset(playedPart, baseOffset + barHeight / 2),
      handleHeight,
      colors.handlePaint,
    );
  }
}

extension RelativePositionExtensions on BuildContext {
  Duration calcRelativePosition(
    Duration videoDuration,
    Offset? globalPosition,
  ) {
    if (globalPosition == null) {
      debugPrint('calcRelativePosition: globalPosition为null，返回Duration.zero');
      return Duration.zero;
    }

    final box = findRenderObject()! as RenderBox;
    final Offset tapPos = box.globalToLocal(globalPosition);
    final double relative = tapPos.dx / box.size.width;
    final Duration position = videoDuration * relative;

    debugPrint('calcRelativePosition计算:');
    debugPrint('  - videoDuration: $videoDuration');
    debugPrint('  - globalPosition: $globalPosition');
    debugPrint('  - box.size: ${box.size}');
    debugPrint('  - tapPos: $tapPos');
    debugPrint('  - relative: $relative');
    debugPrint('  - 计算结果: $position');
    // if (globalPosition == null) return Duration.zero;
    // final box = findRenderObject()! as RenderBox;
    // final Offset tapPos = box.globalToLocal(globalPosition);
    // final double relative = tapPos.dx / box.size.width;
    // final Duration position = videoDuration * relative;
    // return position;
    return position;
  }
}